<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hadoop3.0入门,">










<meta name="description" content="本文为慕课网《快速入门Hadoop3.0大数据处理》的第四章、第五章、第六章，主要讲解：Hadoop三大组件详解该课程地址：https://www.imooc.com/learn/1159">
<meta name="keywords" content="Hadoop3.0入门">
<meta property="og:type" content="article">
<meta property="og:title" content="【三】快速入门Hadoop3.0大数据处理——Hadoop三大组件详解">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/12/24/hadoop3.0-step-by-step-3/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为慕课网《快速入门Hadoop3.0大数据处理》的第四章、第五章、第六章，主要讲解：Hadoop三大组件详解该课程地址：https://www.imooc.com/learn/1159">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191224164052467.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191224170224895.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191224163837127.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191224170743380.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191225090109966.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191225094213272.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191225095042808.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191225170431032.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191225173011724.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226081248918.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226082215806.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226113851845.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226114754781.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226114958623.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226120115643.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226120325263.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226120556333.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226130754624.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226150319980.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226150411551.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226150854469.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226152002637.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226152959684.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226154420442.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191226162106969.jpg">
<meta property="og:updated_time" content="2019-12-26T08:21:24.052Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【三】快速入门Hadoop3.0大数据处理——Hadoop三大组件详解">
<meta name="twitter:description" content="本文为慕课网《快速入门Hadoop3.0大数据处理》的第四章、第五章、第六章，主要讲解：Hadoop三大组件详解该课程地址：https://www.imooc.com/learn/1159">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20191224164052467.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/12/24/hadoop3.0-step-by-step-3/">





  <title>【三】快速入门Hadoop3.0大数据处理——Hadoop三大组件详解 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/12/24/hadoop3.0-step-by-step-3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【三】快速入门Hadoop3.0大数据处理——Hadoop三大组件详解</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-12-24T05:53:30+08:00">
                2019-12-24
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Hadoop/" itemprop="url" rel="index">
                    <span itemprop="name">Hadoop</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为慕课网《快速入门Hadoop3.0大数据处理》的第四章、第五章、第六章，主要讲解：Hadoop三大组件详解<br>该课程地址：<a href="https://www.imooc.com/learn/1159" target="_blank" rel="noopener">https://www.imooc.com/learn/1159</a></p>
<a id="more"></a>

<h2 id="分布式存储-HDFS-详解"><a href="#分布式存储-HDFS-详解" class="headerlink" title="分布式存储(HDFS)详解"></a>分布式存储(HDFS)详解</h2><h3 id="HDFS简介"><a href="#HDFS简介" class="headerlink" title="HDFS简介"></a>HDFS简介</h3><blockquote>
<p>HDFS: Hadoop Distributed File System —— 管理多台机器上的文件</p>
</blockquote>
<ol>
<li><p>单台机器的存储能力是有限的，一般为512G、1T等等；如果有大量数据，就需要在多台机器上存储，但管理和维护比较麻烦。</p>
</li>
<li><p>HDFS的含义: 是一种允许文件通过网络在多台主机上分享的文件系统，可让多机器上的多用户分享文件和存储空间</p>
</li>
<li><p>HDFS的两个特性： 透明性(访问多台机器上的文件如同访问一台机器上的文件，对用户而言无任何差别)；容错性(即使集群中的某些节点宕机了，数据和系统仍可正常运行)</p>
</li>
<li><p>分布式文件管理系统有很多，HDFS只是其中一种实现，HDFS不适合存储小文件</p>
</li>
</ol>
<h3 id="HDFS的Shell介绍与操作"><a href="#HDFS的Shell介绍与操作" class="headerlink" title="HDFS的Shell介绍与操作"></a>HDFS的Shell介绍与操作</h3><ol>
<li>HDFS的Shell的基本使用格式<figure class="highlight vala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># -xxx表示具体的命令，类似于Linux的命令</span></span><br><span class="line"><span class="meta"># schema://authority/path 表示HDFS中的落印信息。</span></span><br><span class="line"><span class="meta"># HDFS的schema是hdfs，authority是NameNode的节点IP和对应的端口号，path是我们要操作的路径信息</span></span><br><span class="line">bin/hdfs dfs -xxx schema:<span class="comment">//authority/path</span></span><br><span class="line"><span class="meta"># 上述命令的简写格式为(其中/path前的/表示HDFS的根目录)</span></span><br><span class="line">bin/hdfs dfs -xxx /path</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>HDFS的Shell的基本使用格式如下图：<br><img src="/blog/images/20191224164052467.jpg" alt="HDFS的Shell的基本使用格式"></p>
<ol start="2">
<li><p>常见的HDFS中Shell命令</p>
<figure class="highlight diff"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="deletion">-ls  查询指定路径信息</span></span><br><span class="line"><span class="deletion">-put 从本地上传文件到HDFS</span></span><br><span class="line"><span class="deletion">-cat 查看HDFS文件内容</span></span><br><span class="line"><span class="deletion">-get 下载HDFS文件到本地</span></span><br><span class="line"><span class="deletion">-mkdir [-p] 在HDFS中创建文件夹</span></span><br><span class="line"><span class="deletion">-rm [-r] 删除HDFS中的文件/文件夹</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>每次都需要输入bin/hdfs太麻烦，可按照如下配置/etc/profile后，直接使用hdfs命令即可<br><img src="/blog/images/20191224170224895.jpg" alt="常见的HDFS中Shell操作"></p>
</li>
<li><p>常见的HDFS中Shell操作</p>
<figure class="highlight jboss-cli"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 查看HDFS根目录下的文件信息</span></span><br><span class="line">bin/hdfs dfs -ls hdfs:<span class="string">//hadoop000</span><span class="function">:9000</span>/</span><br><span class="line"><span class="comment"># 上传本机当前目录下的README.txt到HDFS根目录下</span></span><br><span class="line">bin/hdfs dfs -put README.txt hdfs:<span class="string">//hadoop000</span><span class="function">:9000</span>/</span><br><span class="line"><span class="comment"># 查看HDFS根目录下README.txt的内容</span></span><br><span class="line">bin/hdfs dfs -cat <span class="string">/README.txt</span></span><br><span class="line"><span class="comment"># 下载HDFS根目录下README.txt的内容到本地</span></span><br><span class="line">hdfs dfs -get <span class="string">/README.txt</span> <span class="string">./</span></span><br><span class="line">hdfs dfs -mkdir <span class="string">/data</span></span><br><span class="line">hdfs dfs -rm -r <span class="string">/data</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>常见的HDFS中Shell操作的截图如下：<br><img src="/blog/images/20191224163837127.jpg" alt="常见的HDFS中Shell操作"><br><img src="/blog/images/20191224170743380.jpg" alt="常见的HDFS中Shell操作"></p>
<h3 id="HDFS体系结构详解"><a href="#HDFS体系结构详解" class="headerlink" title="HDFS体系结构详解"></a>HDFS体系结构详解</h3><table>
<thead>
<tr>
<th>HDFS中的三大进程</th>
<th>NameNode</th>
<th>SecondaryNameNode</th>
<th>DataNode</th>
</tr>
</thead>
<tbody><tr>
<td>存在位置</td>
<td>主节点</td>
<td>主节点</td>
<td>从节点</td>
</tr>
<tr>
<td>作用</td>
<td>是整个文件系统的管理节点，它主要维护着整个文件系统的文件目录树，文件/目录的元信息，每个文件对应的数据块block列表，并且还负责接收用户的操作请求。</td>
<td>主要负责定期地把edits文件中的内容合并到fsimage中。这个合并操作称为checkpoint，在合并时会对edits中的内容进行转换，生成新的内容保存到fsimage文件中</td>
<td>提供真实文件数据的存储服务，一般说DataNode即代表从节点</td>
</tr>
<tr>
<td>说明</td>
<td>HDFS的这些信息默认都存放在内存中，但也会在硬盘中保存这些信息，主要存放在以下四个文件中：fsimage、edits、seed_txid、VERSION</td>
<td>checkpoint触发的两种情况：距上一次checkpoint间隔已到1小时；对HDFS已经进行了100万次写操作；</td>
<td>HDFS会按照固定大小，顺序对文件进行划分并编号，划分好的每一个块称为一个block，HDFS默认block大小是128M。 每个block默认3个副本，可通过hdfs-site.xml调整副本数</td>
</tr>
<tr>
<td>总结</td>
<td>NameNode维护了两份关系</td>
<td>第一份关系——File和Block list的关系(即文件和数据块的对应关系)，对应的关系信息存储在fsimage和edits文件中(当NameNode启动时会把这2个文件中的内容加载到内存中)</td>
<td>第二份关系——DataNode与Block的关系(当DataNode启动时，会把当前节点上的Block信息和节点信息上报给NameNode)</td>
</tr>
</tbody></table>
<ol>
<li>NameNode在硬盘中保存的信息主要包含以下四个文件：fsimage(某一时刻NameNode在内存中的元数据镜像)，edits(用户对HDFS的写操作记录，但不记录查询操作)，seed_txid(格式化NameNode后内容默认为0，存储edits文件名后半部分数字，主要是用于NameNode重启时，按照seed_txid中存储的数字，顺序加载对应的edits文件)，VERSION(保存HDFS的版本信息)。这些文件存放的路径是/data/hadoop_repo/dfs/name/current/下。以上文件保存的路径默认是由hdfs-default.xml文件中的dfs.namenode.name.dir属性控制，但可以通过hdfs-site.xml文件进行扩展改变</li>
</ol>
<p>可通过浏览器查看文件的数据块信息，如下图：<br><img src="/blog/images/20191225090109966.jpg" alt="通过浏览器查看文件的数据块信息"></p>
<ol start="2">
<li>在NameNode的HA架构(即高可用架构)中是没有SecondaryNameNode进程的，这个合并操作是由standby NameNode负责实现的。</li>
</ol>
<h2 id="分布式计算-MapReduce-详解"><a href="#分布式计算-MapReduce-详解" class="headerlink" title="分布式计算(MapReduce)详解"></a>分布式计算(MapReduce)详解</h2><h3 id="什么是MapReduce"><a href="#什么是MapReduce" class="headerlink" title="什么是MapReduce"></a>什么是MapReduce</h3><blockquote>
<p>MapReduce是一种分布式计算模型，由Google提出，主要用于搜索领域，解决海量数据的计算问题<br>MapReduce是分布式运行的，由两个阶段组成：Map和Reduce。这两个阶段在代码层面的体现就是两个类。<br>MapReduce框架都有默认实现，用户只需要覆盖map()和reduce()两个函数，即可实现分布式计算，非常简单</p>
</blockquote>
<h3 id="MapReduce原理分析"><a href="#MapReduce原理分析" class="headerlink" title="MapReduce原理分析"></a>MapReduce原理分析</h3><ol>
<li><p>先举个例子<br><img src="/blog/images/20191225094213272.jpg" alt="MapReduce实例"></p>
</li>
<li><p>MapReduce原理图<br><img src="/blog/images/20191225095042808.jpg" alt="MapReduce原理图"></p>
</li>
</ol>
<p>说明如下：</p>
<blockquote>
<p>a. split是文件的逻辑划分，block是文件的物理划分，默认情况下1个split对应1个block，并且它们的大小是相同的。<br>b. split的作用：一个split对应一个map任务。划分split的作用就是创建map任务，每个map任务负责读取并处理其所对应的split所对应的block中的数据。<br>c. shuffle: 本质是一个线程，负责将map阶段的计算结果拉取到reduce阶段进行汇总处理。<br>d. map阶段会对数据进行分类，每个shuffle只拉取各map端的一类数据，交给某一个reduce处理同一类数据；不同种类的数据会分发给不同的reduce进行处理<br>e. reduce将最终计算结果存储到HDFS的一个目录下，每个reduce任务会在这个目录下产生一个结果文件</p>
</blockquote>
<p>一个 block ======对应======&gt; 一个split ======对应======&gt; 一个map </p>
<ol start="3">
<li><p>单文件WordCount案例执行过程如下图<br><img src="/blog/images/20191225170431032.jpg" alt="单文件WordCount案例执行过程如下图"></p>
</li>
<li><p>MapReduce之map阶段执行过程的文字说明如下：</p>
<blockquote>
<p>a. 框架会把输入文件(夹)划分为多个InputSplit(默认每个Block对应一个InputSplit)。通过RecordReader类，把每个InputSplit解析成一个个&lt;k1,v1&gt;对(默认每一行会被解析成一个&lt;k1,v1&gt;,其中k1为行的偏移量，v1为该行的内容)<br>b. 框架调用Mapper类中的map()函数，mao函数的形参是&lt;k1,v1&gt;，输出是&lt;k2,v2&gt;。一个InputSplit对应一个map任务。——————需要开发人员实现<br>c. 框架对map函数输出的&lt;k2,v2&gt;进行分区。不同分区中的&lt;k2,v2&gt;由不同的reduce任务处理，默认只有1个分区<br>d. 框架对每个分区中的数据，按照k2进行局部排序、局部分组(指的是相同k2的v2分成一个组)<br>e. 在map节点，框架可以执行reduce规约，此步骤为可选项，默认不开启。<br>f. 框架会把map任务输出的&lt;k2,v2&gt;写入到linux的磁盘文件中。至此，整个Map阶段执行完成。</p>
</blockquote>
</li>
<li><p>MapReduce之reduce阶段执行过程的文字说明如下：</p>
<blockquote>
<p>a. 框架对所有map任务的输出，按照不同的分区，通过网络copy到不同的reduce节点，这个过程称为shuffle。<br>b. 框架对reduce端接收到的相同分区的&lt;k2,v2&gt;数据进行合并、全局排序、全局分组<br>c. 框架调用Reducer类中的reduce()方法，输入&lt;k2,{v2…}&gt;,输出&lt;k3,v3&gt;。一个&lt;k2,{v2…}&gt;调用一次reduce函数。——————需要开发人员实现<br>d. 框架把reduce方法的输出保存到HDFS中。至此，整个reduce阶段执行完成。</p>
</blockquote>
</li>
<li><p>多文件WordCount案例执行过程如下图<br><img src="/blog/images/20191225173011724.jpg" alt="多文件WordCount案例执行过程如下图"></p>
</li>
</ol>
<h3 id="Shuffle过程分析"><a href="#Shuffle过程分析" class="headerlink" title="Shuffle过程分析"></a>Shuffle过程分析</h3><p>Shuffle过程如下图：<br><img src="/blog/images/20191226081248918.jpg" alt="Shuffle过程"></p>
<p>注意：上图中split经过map后，会将&lt;k2,v2&gt;的数据临时存储到buffer in memory(默认100M)，当其容量达到80%，则写入到本地磁盘</p>
<h3 id="WordCount代码开发"><a href="#WordCount代码开发" class="headerlink" title="WordCount代码开发"></a>WordCount代码开发</h3><ol>
<li><p>创建一个maven-archetype-quickstart骨架的Maven项目<br><img src="/blog/images/20191226082215806.jpg" alt="创建Maven项目"></p>
</li>
<li><p>MapReduce在代码层面的代码就是对应的两个类：MyMapper和MyReducer类</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.apache.hadoop.io.LongWritable;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.io.Text;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.mapreduce.Mapper;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>创建自定义Mapper类，需要继承自Hadoop的Mapper类，</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>其中Mapper的泛型参数为k1,v1,k2,v2</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>其中k1为每行的行首的偏移量，是一个整数，对应到Hadoop中的数据类型就是LongWritable</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>v1为每行的内容，wordCount这个案例中为文本字符串，对应到Hadoop中的数据类型是Text</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>k2为单词，</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>v2为每个单词的次数</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> */</span></span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">MyMapper</span> <span class="keyword">extends</span> <span class="title">Mapper</span>&lt;<span class="title">LongWritable</span>, <span class="title">Text</span>,<span class="title">Text</span>,<span class="title">LongWritable</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>需要实现map()方法</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>这个map方法就是接受k1，v1，返回k2，v2</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>文件的每一行数据都会调用一次map()方法</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param k1  是每行的行首的偏移量</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param v1  是每行的内容</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param context</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@throws IOException</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@throws InterruptedException</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="code">     */</span></span></span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    protected <span class="keyword">void</span> map(LongWritable k1, Text v1, Context context) throws IOException, InterruptedException &#123;</span><br><span class="line">        <span class="comment">//1. 对获取到的每一行数据进行切割，把单词切割出来</span></span><br><span class="line">        <span class="built_in">String</span>[] words = v1.toString().split(<span class="string">" "</span>);</span><br><span class="line">        <span class="comment">//2. 迭代切割出来的单词数据</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="built_in">String</span> word:words) &#123;</span><br><span class="line">            <span class="comment">//3. 把迭代出来的单词封装成&lt;k2,v2&gt;的形式</span></span><br><span class="line">            Text k2 = <span class="keyword">new</span> Text(word);</span><br><span class="line">            LongWritable v2 = <span class="keyword">new</span> LongWritable(<span class="number">1</span>L);</span><br><span class="line">            System.out.println(<span class="string">"k2:"</span>+word+<span class="string">",v2:1"</span>);</span><br><span class="line">            <span class="comment">//4. 通过context将&lt;k2,v2&gt;写出去</span></span><br><span class="line">            context.write(k2,v2);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> *  </span>创建自定义Reducer类，需要继承自Hadoop的Reducer类，</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> *  </span>其中Reducer的泛型参数为k2,v2,k3,v3</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> *  </span>其中k2,v2为map方法的输出</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> *  </span>k3,v3为最终结果即hello 2</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> */</span></span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">MyReducer</span> <span class="keyword">extends</span> <span class="title">Reducer</span>&lt;<span class="title">Text</span>, <span class="title">LongWritable</span>, <span class="title">Text</span>, <span class="title">LongWritable</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>需要实现reduce()方法：针对v2s的数据进行累加求和，并且最终把数据转化为k3,v3写出去</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>这个reduce方法就是接受k2，v2s，返回k3，v3</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>唯一的k2有多少个，这个方法就执行多少次</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param k2</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param v2s 相同k2的所有v2的集合</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param context</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@throws IOException</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@throws InterruptedException</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="code">     */</span></span></span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    protected <span class="keyword">void</span> reduce(Text k2, <span class="built_in">Iterable</span>&lt;LongWritable&gt; v2s, Context context) throws IOException, InterruptedException &#123;</span><br><span class="line">        <span class="comment">// 1. 创建一个sum变量，保存v2s的累加和</span></span><br><span class="line">        long sum = <span class="number">0</span>L;</span><br><span class="line">        <span class="keyword">for</span> (LongWritable v2:v2s) &#123;</span><br><span class="line">            sum += v2.<span class="keyword">get</span>();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 2. 封装为k3,v3</span></span><br><span class="line">        Text k3 = k2;</span><br><span class="line">        LongWritable v3 = <span class="keyword">new</span> LongWritable(sum);</span><br><span class="line">        System.out.println(<span class="string">"k3:"</span>+k3.toString()+<span class="string">",v3:"</span>+sum);</span><br><span class="line">        <span class="comment">// 3. 将k3,v3写出去</span></span><br><span class="line">        context.write(k3, v3);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>引入Hadoop依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--Hadoop client依赖--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.hadoop<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>hadoop-client<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.2.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">  <span class="comment">&lt;!--表示只在编译时使用该依赖，在执行及打包时都不使用--&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">scope</span>&gt;</span>provided<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>将map和reduce组装为一个job并执行</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.apache.hadoop.conf.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.fs.Path;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.io.LongWritable;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.io.Text;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.mapreduce.Job;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</span><br><span class="line"><span class="keyword">import</span> org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>Hadoop3.0下实现WordCount(单词计数)功能</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> *</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>需求：读取HDFS上的hello.txt文件，计算该文件中每个单词出现的总次数</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> *</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>hello.txt文件内容如下：</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>hello me</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>hello </span>you<span class="markdown"></span></span></span><br><span class="line"><span class="comment"><span class="markdown"> *</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>最终输出的结果形式如下：</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>hello 2</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>me 1</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span></span>you<span class="markdown"> 1</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> *</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> */</span></span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">WordCountJob</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>将map和reduce组装为一个job</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param args</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="code">     */</span></span></span></span><br><span class="line">    public <span class="keyword">static</span> <span class="keyword">void</span> main( <span class="built_in">String</span>[] args ) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(args.length != <span class="number">2</span>)&#123;</span><br><span class="line">            System.out.println(<span class="string">"参数不足，需要接收HDFS的输入路径和输出路径两个参数"</span>);</span><br><span class="line">            <span class="comment">//程序退出</span></span><br><span class="line">            System.exit(<span class="number">100</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 1. job需要的配置参数</span></span><br><span class="line">            Configuration conf = <span class="keyword">new</span> Configuration();</span><br><span class="line">            <span class="comment">// 2. 创建一个job</span></span><br><span class="line">            Job job = Job.getInstance(conf);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 指定当前类</span></span><br><span class="line">            <span class="comment">// 注意：这一行必须设置，否则在集群中执行时找不到WordCountJob这个类</span></span><br><span class="line">            job.setJarByClass(WordCountJob.<span class="keyword">class</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 3. 指定输入的HDFS路径(可以是文件，也可以是路径)</span></span><br><span class="line">            FileInputFormat.setInputPaths(job, <span class="keyword">new</span> Path(args[<span class="number">0</span>]));</span><br><span class="line">            <span class="comment">// 4. 指定输出的HDFS路径(只能指定一个不存在的目录，如果该目录存在，则程序会报错)</span></span><br><span class="line">            FileOutputFormat.setOutputPath(job, <span class="keyword">new</span> Path(args[<span class="number">1</span>]));</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 5. 指定map相关的代码</span></span><br><span class="line">            job.setMapperClass(MyMapper.<span class="keyword">class</span>);</span><br><span class="line">            <span class="comment">// 指定(map的输出)k2的类型</span></span><br><span class="line">            job.setMapOutputKeyClass(Text.<span class="keyword">class</span>);</span><br><span class="line">            <span class="comment">// 指定(map的输出)v2的类型</span></span><br><span class="line">            job.setMapOutputValueClass(LongWritable.<span class="keyword">class</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 6. 指定reduce相关的代码</span></span><br><span class="line">            job.setReducerClass(MyReducer.<span class="keyword">class</span>);</span><br><span class="line">            <span class="comment">// 指定reduce的输出(即最终输出)k3的类型</span></span><br><span class="line">            job.setOutputKeyClass(Text.<span class="keyword">class</span>);</span><br><span class="line">            <span class="comment">// 指定reduce的输出(即最终输出)v3的类型</span></span><br><span class="line">            job.setOutputValueClass(LongWritable.<span class="keyword">class</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 7. 提交job</span></span><br><span class="line">            job.waitForCompletion(<span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>修改pom文件，通过maven打包代码</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">build</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">plugins</span>&gt;</span></span><br><span class="line">			<span class="comment">&lt;!-- compiler插件, 设定JDK版本 --&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">plugin</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.maven.plugins<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>maven-compiler-plugin<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">version</span>&gt;</span>2.3.2<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">configuration</span>&gt;</span></span><br><span class="line">					<span class="tag">&lt;<span class="name">encoding</span>&gt;</span>UTF-8<span class="tag">&lt;/<span class="name">encoding</span>&gt;</span></span><br><span class="line">					<span class="tag">&lt;<span class="name">source</span>&gt;</span>1.8<span class="tag">&lt;/<span class="name">source</span>&gt;</span></span><br><span class="line">					<span class="tag">&lt;<span class="name">target</span>&gt;</span>1.8<span class="tag">&lt;/<span class="name">target</span>&gt;</span></span><br><span class="line">					<span class="tag">&lt;<span class="name">showWarnings</span>&gt;</span>true<span class="tag">&lt;/<span class="name">showWarnings</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br><span class="line">			<span class="tag">&lt;/<span class="name">plugin</span>&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">plugin</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>maven-assembly-plugin<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">configuration</span>&gt;</span></span><br><span class="line">					<span class="tag">&lt;<span class="name">descriptorRefs</span>&gt;</span></span><br><span class="line">						<span class="tag">&lt;<span class="name">descriptorRef</span>&gt;</span>jar-with-dependencies<span class="tag">&lt;/<span class="name">descriptorRef</span>&gt;</span></span><br><span class="line">					<span class="tag">&lt;/<span class="name">descriptorRefs</span>&gt;</span></span><br><span class="line">					<span class="tag">&lt;<span class="name">archive</span>&gt;</span></span><br><span class="line">						<span class="tag">&lt;<span class="name">manifest</span>&gt;</span></span><br><span class="line">							<span class="tag">&lt;<span class="name">mainClass</span>&gt;</span><span class="tag">&lt;/<span class="name">mainClass</span>&gt;</span></span><br><span class="line">						<span class="tag">&lt;/<span class="name">manifest</span>&gt;</span></span><br><span class="line">					<span class="tag">&lt;/<span class="name">archive</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;<span class="name">executions</span>&gt;</span></span><br><span class="line">					<span class="tag">&lt;<span class="name">execution</span>&gt;</span></span><br><span class="line">						<span class="tag">&lt;<span class="name">id</span>&gt;</span>make-assembly<span class="tag">&lt;/<span class="name">id</span>&gt;</span></span><br><span class="line">						<span class="tag">&lt;<span class="name">phase</span>&gt;</span>package<span class="tag">&lt;/<span class="name">phase</span>&gt;</span></span><br><span class="line">						<span class="tag">&lt;<span class="name">goals</span>&gt;</span></span><br><span class="line">							<span class="tag">&lt;<span class="name">goal</span>&gt;</span>single<span class="tag">&lt;/<span class="name">goal</span>&gt;</span></span><br><span class="line">						<span class="tag">&lt;/<span class="name">goals</span>&gt;</span></span><br><span class="line">					<span class="tag">&lt;/<span class="name">execution</span>&gt;</span></span><br><span class="line">				<span class="tag">&lt;/<span class="name">executions</span>&gt;</span></span><br><span class="line">			<span class="tag">&lt;/<span class="name">plugin</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;/<span class="name">plugins</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">build</span>&gt;</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>Maven项目打包过程如下图：<br><img src="/blog/images/20191226113851845.jpg" alt="Maven项目打包过程"></p>
<ol start="6">
<li><p>上传hadoop3.0-step-by-step-1.0-SNAPSHOT.jar包到主节点上<br><img src="/blog/images/20191226114754781.jpg" alt="上传jar包到Hadoop服务器"></p>
</li>
<li><p>启动Hadoop，创建hello.txt并上传到HDFS上<br><img src="/blog/images/20191226114958623.jpg" alt="创建hello.txt并上传到HDFS上"></p>
</li>
<li><p>提交Hadoop任务，执行程序</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"># 提交Hadoop任务的命令格式如下：<span class="string">"hadoop jar jar包名称 需要执行入口类的全类名 hdfs输入路径 hdfs输出路径目录(不存在的目录)"</span></span><br><span class="line">hadoop jar hadoop3<span class="number">.0</span>-<span class="built_in">step</span>-by-<span class="built_in">step</span><span class="number">-1.0</span>-SNAPSHOT.jar com.aiolos.WordCountJob hdfs:<span class="comment">//hadoop000:9000/hello.txt  hdfs://hadoop000:9000/out</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>Hadoop任务执行过程如下图：<br><img src="/blog/images/20191226120115643.jpg" alt="Hadoop任务执行过程"></p>
<ol start="9">
<li>查看Hadoop任务执行结果<br><img src="/blog/images/20191226120325263.jpg" alt="查看Hadoop任务执行结果"></li>
</ol>
<p>也可以通过浏览器访问：<a href="http://192.168.126.131:8088/" target="_blank" rel="noopener">http://192.168.126.131:8088/</a> 查看结果<br><img src="/blog/images/20191226120556333.jpg" alt="查看Hadoop任务执行结果"></p>
<h3 id="MapReduce任务日志查看"><a href="#MapReduce任务日志查看" class="headerlink" title="MapReduce任务日志查看"></a>MapReduce任务日志查看</h3><blockquote>
<p>如果在代码中有日志输出，如何在Hadoop集群中查看这些日志呢？</p>
</blockquote>
<ol>
<li>开启yarn的日志聚合功能，把散落在nodemanager节点上的日志统一收集管理，方便查看日志。<br>具体修改如下：<figure class="highlight dts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># 需要修改yarn-site.xml文件，增加的内容如下：</span></span><br><span class="line"><span class="params">&lt;property&gt;</span> </span><br><span class="line">	<span class="params">&lt;name&gt;</span>yarn.log-aggregation-enable<span class="params">&lt;/name&gt;</span>  </span><br><span class="line">	<span class="params">&lt;value&gt;</span>true<span class="params">&lt;/value&gt;</span></span><br><span class="line"><span class="params">&lt;/property&gt;</span></span><br><span class="line"><span class="params">&lt;property&gt;</span></span><br><span class="line">	<span class="params">&lt;name&gt;</span>yarn.log.server.url<span class="params">&lt;/name&gt;</span></span><br><span class="line">	<span class="params">&lt;value&gt;</span>http:<span class="comment">//hadoop000:19888/jobhistory/logs/&lt;/value&gt;</span></span><br><span class="line"><span class="params">&lt;/property&gt;</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>操作过程如下图：<br><img src="/blog/images/20191226130754624.jpg" alt="修改yarn-site.xml文件"></p>
<ol start="2">
<li><p>重启Hadoop集群，操作过程如下图<br><img src="/blog/images/20191226150319980.jpg" alt="修改yarn-site.xml文件"></p>
</li>
<li><p>在所有节点都需要启动historyserver进程，命令如下： </p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sbin/mr-jobhistory-daemon<span class="selector-class">.sh</span> start historyserver</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>操作过程如下图：<br><img src="/blog/images/20191226150411551.jpg" alt="启动historyserver进程的过程"></p>
<ol start="4">
<li>删除/out目录后，重新执行程序<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">hadoop jar hadoop3.<span class="number">0</span>-step-by-step-<span class="number">1.0</span>-SNAPSHOT<span class="selector-class">.jar</span> com<span class="selector-class">.aiolos</span><span class="selector-class">.WordCountJob</span> hdfs:<span class="comment">//hadoop000:9000/hello.txt  hdfs://hadoop000:9000/out</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>操作过程如下图：<br><img src="/blog/images/20191226150854469.jpg" alt="重新执行程序"></p>
<ol start="5">
<li>通过浏览器访问 <a href="http://192.168.126.131:8088/" target="_blank" rel="noopener">http://192.168.126.131:8088/</a> 查看日志<blockquote>
<p>注意： 需要在本地的hosts文件中配置Hadoop节点与ip地址的映射关系</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191226152002637.jpg" alt="查看日志"></p>
<h3 id="停止Hadoop集群中正在执行的任务"><a href="#停止Hadoop集群中正在执行的任务" class="headerlink" title="停止Hadoop集群中正在执行的任务"></a>停止Hadoop集群中正在执行的任务</h3><blockquote>
<p>在某些特殊情况下，如何停止Hadoop集群中正在执行的任务? </p>
</blockquote>
<ol>
<li><p>查看Hadoop集群中正在执行的任务</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yarn <span class="built_in">application</span> -<span class="built_in">list</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>停止Hadoop集群中正在执行的任务</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yarn <span class="built_in">application</span> -kill &lt;application_Id号&gt;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>注意： 在命令行ctrl+c无法停止程序，因为程序已经提交到Hadoop集群运行了</p>
<p>操作过程如下图：<br><img src="/blog/images/20191226152959684.jpg" alt="停止Hadoop集群中正在执行的任务"></p>
<h3 id="Hadoop的序列化机制"><a href="#Hadoop的序列化机制" class="headerlink" title="Hadoop的序列化机制"></a>Hadoop的序列化机制</h3><ol>
<li>MapReduce任务执行过程中的所有IO操作，如下图：<br><img src="/blog/images/20191226154420442.jpg" alt="MapReduce任务执行过程中的所有IO操作"></li>
</ol>
<blockquote>
<p>从上图可知，影响MapReduce任务执行效率的主要因素就是磁盘IO</p>
</blockquote>
<ol start="2">
<li><p>由于当程序与磁盘进行数据的读写操作时，要对数据进行序列化和反序列化。 虽然无法避免磁盘IO，但可以优化数据的序列化和反序列化</p>
<blockquote>
<p>序列化：把内存的数据写入磁盘文件中，就需要对数据序列化。序列化即是把内存中的对象信息转换为二进制形式保存到文件中。<br>反序列化：把磁盘文件读入内存中，就需要对数据反序列化。 </p>
</blockquote>
</li>
<li><p>Java的序列化机制会把对象的父类、超类等整个继承体系信息都保存下来，数据很冗余，所以导致写入文件中的数据也多————这就是可以优化的地方。</p>
</li>
<li><p>Hadoop的序列化机制并没有使用Java序列化机制，它尽量精简了对象的存储数据，不再保持继承体系，提高了数据的读写性能。 这就是Hadoop自己设计数据类型的原因。</p>
</li>
<li><p>Hadoop序列化机制与Java序列化机制的优缺点比较</p>
</li>
</ol>
<table>
<thead>
<tr>
<th>优缺点</th>
<th>Hadoop序列化机制优点</th>
<th>Java序列化机制缺点</th>
</tr>
</thead>
<tbody><tr>
<td>一</td>
<td>紧凑： 高效使用存储空间</td>
<td>不精简：附加信息多，不太适合随机访问</td>
</tr>
<tr>
<td>二</td>
<td>快速： 读写数据的额外开销小</td>
<td>存储空间大：递归地输出类的超类描述直到不再有超类。保存类的所有继承体系</td>
</tr>
<tr>
<td>三</td>
<td>可扩展：可透明地读取老格式的数据</td>
<td>扩展性差：Hadoop中的Writable可以方便用户自定义</td>
</tr>
<tr>
<td>四</td>
<td>互操作： 支持多语言的交互</td>
<td></td>
</tr>
</tbody></table>
<p><strong>结论：Hadoop不用Java中的数据类型、不使用Java序列化机制的原因：Java序列化太冗余，存储的数据太多。所以Hadoop自己创建了数据类型，自己实现了序列化机制</strong></p>
<h2 id="资源调度器-Yarn-详解"><a href="#资源调度器-Yarn-详解" class="headerlink" title="资源调度器(Yarn)详解"></a>资源调度器(Yarn)详解</h2><p>MapReduce在执行过程中，需要通过Yarn来获取资源。</p>
<ol>
<li><p>Yarn的功能: 负责管理整个集群的资源，主要包括内存、CPU。当一个任务执行时，它会向Yarn申请资源，Yarn负责分配资源给这个任务。</p>
</li>
<li><p>Yarn目前支持三种调度器：</p>
<blockquote>
<p>Yarn中的调度器是针对任务的调度器</p>
</blockquote>
</li>
</ol>
<table>
<thead>
<tr>
<th>三种调度器</th>
<th>FIFOScheduler</th>
<th>CapacityScheduler</th>
<th>FairScheduler</th>
</tr>
</thead>
<tbody><tr>
<td>含义</td>
<td>先进先出(first in,first out)调度策略。</td>
<td>可以看作是FIFOScheduler的多队列版本。</td>
<td>多队列、多用户共享资源</td>
</tr>
<tr>
<td>特点</td>
<td>将所有资源构成一个队列，执行先进先出调度策略</td>
<td>将所有资源划分为多个队列，在每个队列内都执行FIFOScheduler调度策略</td>
<td>动态分配资源给任务</td>
</tr>
<tr>
<td>默认</td>
<td>Hadoop 1.X的默认调度器</td>
<td>Hadoop 2.X/3.X的默认调度器</td>
<td></td>
</tr>
<tr>
<td>图示</td>
<td><img src="/blog/images/20191226162106969.jpg" alt="Yarn三种调度器"></td>
<td></td>
<td></td>
</tr>
</tbody></table>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Hadoop3-0入门/" rel="tag"># Hadoop3.0入门</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/12/23/hadoop3.0-step-by-step-2/" rel="next" title="【二】快速入门Hadoop3.0大数据处理——Hadoop3.0安装部署">
                <i class="fa fa-chevron-left"></i> 【二】快速入门Hadoop3.0大数据处理——Hadoop3.0安装部署
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/12/25/java-interview-offer-5/" rel="prev" title="【五】剑指Java面试Offer直通车-数据库相关">
                【五】剑指Java面试Offer直通车-数据库相关 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#分布式存储-HDFS-详解"><span class="nav-number">1.</span> <span class="nav-text">分布式存储(HDFS)详解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#HDFS简介"><span class="nav-number">1.1.</span> <span class="nav-text">HDFS简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HDFS的Shell介绍与操作"><span class="nav-number">1.2.</span> <span class="nav-text">HDFS的Shell介绍与操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HDFS体系结构详解"><span class="nav-number">1.3.</span> <span class="nav-text">HDFS体系结构详解</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分布式计算-MapReduce-详解"><span class="nav-number">2.</span> <span class="nav-text">分布式计算(MapReduce)详解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是MapReduce"><span class="nav-number">2.1.</span> <span class="nav-text">什么是MapReduce</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MapReduce原理分析"><span class="nav-number">2.2.</span> <span class="nav-text">MapReduce原理分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Shuffle过程分析"><span class="nav-number">2.3.</span> <span class="nav-text">Shuffle过程分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#WordCount代码开发"><span class="nav-number">2.4.</span> <span class="nav-text">WordCount代码开发</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MapReduce任务日志查看"><span class="nav-number">2.5.</span> <span class="nav-text">MapReduce任务日志查看</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#停止Hadoop集群中正在执行的任务"><span class="nav-number">2.6.</span> <span class="nav-text">停止Hadoop集群中正在执行的任务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hadoop的序列化机制"><span class="nav-number">2.7.</span> <span class="nav-text">Hadoop的序列化机制</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#资源调度器-Yarn-详解"><span class="nav-number">3.</span> <span class="nav-text">资源调度器(Yarn)详解</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
